<template>
    <div class="main_container">
        <el-row style="height: 40px;line-height: 40px;margin: 10px 20px 25px 20px;">
            <el-col :span="6">
                <el-radio-group v-model="filterType" @change="radioChange">
                    <el-radio label="1">按条件筛选</el-radio>
                    <el-radio label="2">按日期范围</el-radio>
                </el-radio-group>
            </el-col>
            <el-col :span="7" v-if="filterType=='1'">
                <el-select style="width: 280px;" v-model="order_type" placeholder="请选择"
                    @change="typeChange" clearable>
                    <el-option v-for="item in filterTypes" :key="'filter_'+item.value" 
                        :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-col>
            <el-col :span="7" v-else>
                <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" 
                    v-model="dateRange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                    :picker-options="handleTime" @change="dateChange"
                    placeholder="请选择日期范围" style="width: 280px;" clearable></el-date-picker>
            </el-col>
            <el-col :span="11">
                <div style="display: flex;justify-content: end;">
                    <el-radio-group v-model="tableType" size="mini">
                        <el-radio-button label="income">收入</el-radio-button>
                        <el-radio-button label="outcome">支出</el-radio-button>
                    </el-radio-group>
                </div>
            </el-col>
        </el-row>

        <!-- <pie-chart v-show="showEcharts" :pieData="chartData" :customStyle="customStyle" :showLegend="true"></pie-chart> -->

        <div class="common_line"></div>
        <div id="printcontent">
            <el-row style="padding: 20px 10%;">
                <el-col :span="8">
                    <span class="top_title">总收入：￥</span>
                    <span class="money" :class="totalData.total_income<0?'red':'green'">{{ totalData.total_income.toFixed(2) }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="top_title">总支出：￥</span>
                    <span class="money" :class="totalData.total_outcome<0?'red':'green'">{{ totalData.total_outcome.toFixed(2) }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="top_title">总利润：￥</span>
                    <span class="money" :class="totalData.profit<0?'red':'green'">{{ totalData.profit.toFixed(2) }}</span>
                </el-col>
            </el-row>
            <div class="common_line"></div>
            <el-table border :data="tableData" show-summary :summary-method="getSummaries" style="margin-top: 15px;">
                <el-table-column label="时间" align="center" prop="dateName" />
                <el-table-column :formatter="formatValue" v-if="tableType=='income'" label="销售收入" align="center" prop="income" :key="'income' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='income'" label="日常收入" align="center" prop="everyday_income" :key="'everyday_income' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='income'" label="盘点盈收" align="center" prop="stock_check_incr" :key="'stock_check_incr' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='income'" label="采购退货" align="center" prop="pu_return" :key="'pu_return' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='income'" label="销售订金" align="center" prop="reserve_order" :key="'reserve_order' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='income'" label="总收入" align="center" prop="total_income" :key="'total_income' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='outcome'" label="采购支出" align="center" prop="purchase_outlay" :key="'purchase_outlay' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='outcome'" label="日常支出" align="center" prop="everyday_outcome" :key="'everyday_outcome' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='outcome'" label="组装费" align="center" prop="stock_join" :key="'stock_join' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='outcome'" label="拆分费" align="center" prop="stock_split" :key="'stock_split' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='outcome'" label="盘点亏损" align="center" prop="stock_check_decr" :key="'stock_check_decr' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='outcome'" label="销售退货" align="center" prop="sale_return" :key="'sale_return' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='outcome'" label="其他费用" align="center" prop="sale_rebates" :key="'sale_rebates' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='outcome'" label="采购订金" align="center" prop="reserve_purchase" :key="'reserve_purchase' + tableType" />
                <el-table-column :formatter="formatValue" v-if="tableType=='outcome'" label="总支出" align="center" prop="total_outcome" :key="'total_outcome' + tableType" />
                <el-table-column :formatter="formatValue" label="利润" align="center" prop="turnover" />
            </el-table>
        </div>
    </div>
</template>

<script>
import { getBusinessStatistic } from '@/api/statistics'
import pieChart from '@/components/pieChart';
import { getToken } from '@/utils/auth';
import { urlToPdf } from '@/api/common';

export default {
    name: 'businessCount',
    components: {
        pieChart
    },
    data() {
        return {
            filterType: '1',  //1 按条件  2 按日期范围
            filterTypes: [
                {id: 1, label: '今日', value: 'cur_day'},
                {id: 2, label: '本周', value: 'cur_weak'},
                {id: 3, label: '本月', value: 'cur_month'},
                {id: 4, label: '月度', value: 'month'},
                {id: 5, label: '季度', value: 'quarter'},
                {id: 6, label: '年度', value: 'year'},
            ],
            params: {
                corp_id: '',
                start_date: '',
                end_date: '',
                order_type: 'month'
            },
            order_type: 'month',
            tableType: 'income',
            dateRange: [],
            handleTime: {
                disabledDate(date) {
                    //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
                    return date.getTime() > Date.now();
                }
            },
            showEcharts: false,  
            customStyle: {
                width: '600px',
                height: '300px',
                paddingRight: '74px'
            },
            totalData: {
                total_income: 0,  //采购支出
                total_outcome: 0,  //日常支出
                profit: 0  //利润
            },
            tableData: [],
            chartData: []
        }
    },
    created() {
        this.params.corp_id = this.$store.state.corpId
        let nowDate = new Date()
        this.params.start_date = nowDate.getFullYear()+'-01-01'
        this.getData()
    },
    methods: {
        // 补零
        add0(num) {
            if (parseInt(num) < 10){
                num = '0'+ num
            }
            return num
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                    }, 0);
                    sums[index] = sums[index].toFixed(2);
                } else {
                    sums[index] = '--';
                }
            });

            return sums;
        },
        formatValue(row, column, cellValue) {
            // 如果是时间列，直接返回原值
            if (column.property === 'dateName') {
                return cellValue;
            }
            // 否则将值转换为字符串并加上 ￥ 前缀
            // return `￥${cellValue}`;
            if (typeof(cellValue) == 'number'){
                return cellValue.toFixed(2)
            }else{
                return cellValue
            }
            
        },
        // 获取数据
        getData() {
            var that = this
            let nowDate = new Date()
            getBusinessStatistic(this.params).then(res => {
                let resStartDate = res.data.start_date  //接口返回的开始日期
                let resEndDate = res.data.end_date_le  //接口返回的结束日期
                let curYear = nowDate.getFullYear(),
                    curMonth = nowDate.getMonth()+1;
                that.totalData = {
                    total_income: 0,  //采购支出
                    total_outcome: 0,  //日常支出
                    profit: 0  //利润
                }

                let lists = res.data.data.filter(item => {
                    if (that.params.order_type == 'cur_day') {  //当天
                        item.dateName = resEndDate
                        item.type = 'cur_day'
                    }else if (that.params.order_type == 'cur_weak') {  //本周
                        item.dateName = resStartDate+' 至 '+resEndDate
                        item.type = 'cur_weak'
                    }else if (that.params.order_type == 'cur_month') {  //当月，一条数据
                        item.dateName = curYear+'-'+that.add0(curMonth)
                        item.type = 'cur_month'
                    }else if (that.params.order_type == 'day'){  //本月，28~31天
                        item.dateName = curYear+'-'+that.add0(curMonth)+'-'+that.add0(item.date)
                        item.type = 'day'
                    }else if (that.params.order_type == 'month'){ //月度
                        item.type = 'month'
                        item.dateName = item.date + '月'
                    }else if (that.params.order_type == 'quarter'){  //季度
                        item.dateName = '第' + item.date + '季度'
                        item.type = 'quarter'
                    }else if (that.params.order_type == 'year'){ //年度
                        item.dateName = item.date + '年'
                        item.type = 'year'
                    }else if (that.params.order_type == 'customize_date'){ //自定义
                        item.dateName = that.params.start_date+'至'+that.params.end_date
                        item.type = 'customize_date'
                    }
                    item.total_income = (item.income + item.everyday_income + item.stock_check_incr +
                        item.reserve_order + item.pu_return).toFixed(2)
                    item.total_outcome = (item.purchase_outlay + item.everyday_outcome + item.stock_join +
                        item.stock_split + item.stock_check_decr + item.reserve_purchase + 
                        item.sale_return + item.sale_rebates).toFixed(2)

                    that.totalData.total_income = that.$common.plusFloat(that.totalData.total_income, item.total_income)
                    that.totalData.total_outcome = that.$common.plusFloat(that.totalData.total_outcome, item.total_outcome)
                    that.totalData.profit = that.$common.plusFloat(that.totalData.profit, item.turnover)
                    return item
                })

                that.showEcharts = false
                if (that.params.order_type=='month' || that.params.order_type=='quarter'){
                    that.showEcharts = true
                    that.$forceUpdate()
                }
                that.tableData = lists
            })
        },
        radioChange(val) {
            if (val == '1'){
                this.typeChange(this.order_type)
            }else{
                this.showEcharts = false
                this.dateChange(this.dateRange)
            }
        },
        typeChange(val) {
            if (!val) return

            let nowDate = new Date()
            if (val.indexOf("cur_")<0){
                this.params.start_date = nowDate.getFullYear()+'-01-01'
                if(val == 'day'){  //本月，28~31天
                    this.params.start_date = nowDate.getFullYear()+this.add0(nowDate.getMonth()+1)+'-01'
                }
            }else{
                this.params.start_date = ''
            }
            this.params.order_type = val

            this.getData()
        },
        dateChange(value) {
            if(value && value.length){
                this.params.start_date = value[0]
                this.params.end_date = value[1]
                this.params.order_type = 'customize_date'
                this.getData()
            }
            else{
                this.params.start_date = this.params.end_date = null
                this.params.order_type = ''
                this.tableData = []
                this.totalData = {
                    total_income: 0,  //采购支出
                    total_outcome: 0,  //日常支出
                    turnover: 0,  //营业额
                    profit: 0  //利润
                }
            }
        },
        // 导出
        handleExport() {

        },
        // 打印
        handlePrint() {
            urlToPdf({
                corpId: this.params.corp_id,
                pdf_file_add: {
                    unique_order_no: '',
                    unique_type: 'pdf_report',
                    show_filename: '经营状况报表.pdf',
                    req_url: 'https://anhuiyaoying.com/pdf/report.html?corp='+this.params.corp_id+'&type='+this.params.order_type
                },
                print_dict: {},
                domain: 'anhuiyaoying.com',
                cookies_dict: {
                    Authorization_TOKEN: getToken()
                }
            }).then(res => {
                if (res.code == 200){
                    window.open(res.data.pdf_url)
                }else{
                    this.$message.error(res.message)
                }
            })
        },
    }
}
</script>

<style lang="less" scoped>
    @import '../../style/mixin.less';
    .btns {
        float: right;
        height: 40px;
        display: flex;
        align-items: center;
        padding-right: 20px;
    }
    .top_title {
        font-size: 14px;
        color: #606266;
    }
    .money {
        font-size: 20px;
        // color: red;
    }
    .red {
        color: red;
    }
    .green {
        color: @blue;
    }
</style>